var starMap = (function() {
  var A = {};
  var h = 0;
  var hei = $("body").height() - h;
  var wid = $("body").width();
  var maptk;
  var map;
  var geocoder;
  var cityName;
  var cate;
  var rectTool;
  var rects = [];
  var pics = {};
  var overImages = {};
  
  var dbl = false;
  A.initData = function(){
    cate = {cateId: A.local.getParam('cid')};
    rectTool = new T.RectangleTool(map);
    rectTool.addEventListener("draw", function(ev){
      var currRect = ev.currentRectangle;
      rects.push(currRect);
      currRect.enableEdit();
      bindEvent(currRect);
    })
    A.loadData(1);
  };
  A.loadData = function(pageNum){
    A.local.ajax({
      url: '/warInfo/map',
      data: {"cateId": cate.cateId, "pager": {"pageNum": pageNum, "pageSize": 33}},
      callback: function(data){
        var items = data[cate.cateId];
        if(items && items.length > 0){
          items.forEach(function(item, idx){
            var bd = new T.LngLatBounds(new T.LngLat(item.lng, item.lat), new T.LngLat(item.lng2, item.lat2))
            var rect = new T.Rectangle(bd);
            map.addOverLay(rect);
            if(item.pictures && item.pictures[0]){
              pics[idx] = item.pictures[0].url;
            }
            rects.push(rect);
            A.setOverImage(idx);
            bindEvent(rect);
          });
          pageNum ++;
          A.loadData(pageNum);
        }
      }
    });
  };
  
  A.setOverImage = function(idx){
    if(null != overImages[idx]){
      map.removeOverLay(overImages[idx]);
      overImages[idx] = null;
    }
    var overImgPath = pics[idx];
    var rect = rects[idx];
    overImages[idx] = new T.ImageOverlay(overImgPath, rect.getBounds(), {opacity: 1});
    map.addOverLay(overImages[idx]);
  }
  function bindEvent(rect){
    rect.addEventListener("dblclick", function(e){
      if(dbl){
        dbl = false;
        var idx = rects.indexOf(e.target);
        buildUploadImage(function(){
          var fn = this;
          var filenames=new Array();
          var formData = new FormData();
          var files=$('#uploadImage')[0].files;
          if(files.length <= 0) return;
          var totalSize = 0;
          for(var i=0;i<files.length;i++){
            if(files[i].size > 1024*1024*1){
              artDialog.alert("图片文件["+files[i].name+"]不得大于1MB");
              return;
            }
            totalSize+=files[i].size;
            formData.append(files[i].name, files[i]);
            filenames.push(files[i].name);
          }
          if(totalSize > 1024*1024*10){
            artDialog.alert("选择的图片文件总共不得大于10MB");
            return;
          }
          $.ajax({
              url: '/upload/images',
              type: 'POST',
              cache: false,
              data: formData,
              dataType: 'json',
              processData: false,
              contentType: false,
          }).done(function(res) {
            pics[idx] = res.data[0].original;
            A.setOverImage(idx);
          }).fail(function(a,b,c) {
            var msg = "不得上传2MB以上的图片";
            artDialog.alert(msg)
          }).always(function(a,b,c,d){
            buildUploadImage(fn);
          });
        });
        $("#uploadImageDiv #uploadImage").click();
      }else{
        dbl = true;
      }
    });
    rect.addEventListener("click", function(e){
      if(e.target.isEditable()){
        e.target.disableEdit();
      }else{
        e.target.enableEdit();
        $(".tdt-editing-icon").off().on("mouseup mouseout mouseover", function(){
          changeRectImgs();
        });
      }
    });
  }
  function changeRectImgs(){
    rects.forEach(function(rect, idx){
      A.setOverImage(idx);
    });
  }
  function buildUploadImage(fileOnChangeFunc){
    if($("#uploadImageDiv").length > 0){
      $("#uploadImageDiv").remove();
    }
    $("body").append('<div id="uploadImageDiv" style="display:none"></div>');
    $("#uploadImageDiv").html('<input type="file" name="uploadImage" id="uploadImage" accept="image/*">');
    $("#uploadImageDiv #uploadImage").on("change", fileOnChangeFunc);
  }
  
  A.getMap = function(){
    return map;
  };
  
  A.initTools = function() {
    A.local.tuceng();
    A.local.searchAddr();
    $(".tdt-control-copyright").hide();
  }

  A.viewMap = function(tk, id, city, zoom, config) {
    maptk = tk;
    cityName = city;
    $("#" + id).height(hei);
    map = new T.Map(id, config);
    map.centerAndZoom(new T.LngLat(116.40969, 39.89945), zoom);
    map.enableScrollWheelZoom();
    map.disableDoubleClickZoom();
    geocoder = new T.Geocoder();
    geocoder.getPoint(city, A.local.searchResult);
//    map.addEventListener("click", function(e){
//      console.log(JSON.stringify(e.lnglat));
//    });
  };

  A.local = {};
  A.local.searchAddr = function() {
    var dw = new T.Control({
      position : T_ANCHOR_TOP_LEFT
    });
    dw.onAdd = function(map) {
      var div = $('<div class="dwDiv">');
      div.html('<input type="text" id="searchIpt" class="ipt400" placeholder="输入需要定位的地址"> <button class="dwBtn">定位</button>');
      div.append('<br><button class="operBtn addBtn">添加覆盖图</button> <button class="operBtn delBtn">删除覆盖图</button> <button class="operBtn saveBtn">保存覆盖图</button>')
      return div[0];
    };
    map.addControl(dw);
    $(".dwBtn").click(function() {
      var addr=$("#searchIpt").val();
      if(! addr) {
        alert("请输入需定位的地址");
        return;
      }
      geocoder.getPoint(addr, A.local.searchResult);
    });
    $(".saveBtn").click(function() {
      var datas = [];
      rects.forEach(function(rect, idx){
        var sw = rect.getBounds().getSouthWest();
        var ne = rect.getBounds().getNorthEast();
        var data = {"cateId": cate.cateId, "lng": sw.lng, "lat": sw.lat, "lng2": ne.lng, "lat2": ne.lat, "pictures": [{"url": pics[idx]}]};
        datas.push(data);
      });
      console.log(JSON.stringify(datas))
      A.local.ajax({
        url: '/warInfo/adds/'+cate.cateId,
        data: datas,
        callback: function(data){
          artDialog.tips("保存成功")
        }
      });
    });
    $(".addBtn").click(function() {
      rectTool.open();
      artDialog.tips("现在你可以在地图上选取一个矩形区域")
    });
    $(".delBtn").click(function() {
      var bool = true;
      var idxs = [];
      rects.forEach(function(rect, idx){
        if(rect.isEditable()){
          bool = false;
          idxs.splice(0, 0, idx);
        }
      });
      if(bool){
        artDialog.tips("请选中要删除的矩形区域")
        return false;
      }
      artDialog.confirm("确定要删除选中的区域？", function(){
        rects.forEach(function(rect, idx){
          if(rect.isEditable()){
            if(overImages[idx]){
              map.removeOverLay(overImages[idx]);
            }
            map.removeOverLay(rect);
          }
        });
        idxs.forEach(function(idx){
          rects.splice(idx, 1);
          overImages[idx] = overImages[idx + 1];
          pics[idx] = pics[idx + 1];
        });
      });
    });
  };
  A.local.tuceng = function() {
    var tc = new T.Control({
      position : T_ANCHOR_TOP_RIGHT
    });
    tc.onAdd = function(map) {
      var div = $('<div class="tcDiv">');
      div.html('<button class="tcBtn">地<br>图</button>');
      var html = '<div class="tcBtns">';
      html += '<button class="chooseMapBtn" data-type="vec" data-name="地<br>图"><img src=""><br>地图</button>';
      html += '<br><button class="chooseMapBtn" data-type="img" data-name="影<br>像"><img src=""><br>影像</button>';
      html += '<br><button class="chooseMapBtn" data-type="ter" data-name="地<br>形"><img src=""><br>地形</button>';
      div.append(html);
      return div[0];
    };
    map.addControl(tc);
    $(".tcBtn").click(function() {
      $(".tcBtns").slideToggle("fast", function() {
        $(".chooseMapBtn").unbind().click(function() {
          var type = $(this).attr("data-type");
          var name = $(this).attr("data-name");
          $(".tcBtn").html(name);
          $(".tcBtn").click();
          $(this).unbind();
          A.local.changeMapType(type);
        });
      });
    });
  };
  A.local.changeMapType = function(n) {
    var o = parseInt(Math.random() * 7);
    var urlImg = "https://t" + o + ".tianditu.gov.cn/" + n + "_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=" + n + "&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=" + maptk;
    n = "cva";
    var urlName = "https://t" + o + ".tianditu.gov.cn/" + n + "_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=" + n + "&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=" + maptk;
    map.clearLayers();
    var lay1 = new T.TileLayer(urlImg, {
      minZoom : 1,
      maxZoom : 18
    });
    var lay2 = new T.TileLayer(urlName, {
      minZoom : 1,
      maxZoom : 18
    });
    map.addLayer(lay1);
    map.addLayer(lay2);
  };
  A.local.searchResult = function(result) {
    if (result.getStatus() == 0) {
      map.panTo(result.getLocationPoint());
    } else {
      alert(result.getMsg());
    }
  };
  
  A.local.getParam = function(name){
    var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");     
    var r = window.location.search.substr(1).match(reg);
    //search,查询？后面的参数，并匹配正则    
    if(r!=null)
      return  unescape(r[2]); 
    return null;
  };
  A.local.ajax = function(options) {
    $.ajax({
      async: null == options.async ? true : options.async,
      url : options.url,
      contentType : 'application/json',
      data : JSON.stringify(options.data),
      type : 'post',
      dataType : 'json',
      success : function(res) {
        if (res.code == 0) {
          if (options.callback) {
            options.callback(res.data);
          }
        } else {
          alert(res.msg)
        }

      },
      error : function(a, b) {
        console.log(b);
        alert(res.msg)
      }
    });
  };
  return A;
})();